﻿using System;

namespace EmbeddedSharp.Core.Function.Flow
{
    public class ForNode : FuncNode
    {

        public ForNode()
            : base()
        {
            base.Value = "for";
        }

        public override object Evaluate()
        {
            Parameters[Parameters.Count - 1].Evaluate(); // init
            string cond = Parameters[Parameters.Count - 2].Evaluate().ToString();
            string result = string.Empty;

            while (cond.ToLower().Equals("true"))
            {
                try
                {
                    Parameters[Parameters.Count - 4].Evaluate(); // loop body
                }
                catch (BreakException ex)
                {
                    break;
                }
                catch (ContinueException ex)
                {
                    Parameters[Parameters.Count - 3].Evaluate(); // step
                    cond = Parameters[Parameters.Count - 2].Evaluate().ToString();
                    continue;
                }

                Parameters[Parameters.Count - 3].Evaluate(); // step
                cond = Parameters[Parameters.Count - 2].Evaluate().ToString();
            }

            return result;
        }
    }
}
